<!DOCTYPE html>
<html lang="zh-CN">
<!-- 比赛首页 -->

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>足球比赛列表</title>
    <style>
        body {
            font-family: "Segoe UI", sans-serif;
            background: #f9f9f9;
            padding: 20px;
            color: #333;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            /* 水平居中 */
            align-items: flex-start;
            /* 顶部对齐 */
            min-height: 100vh;
            /* 保证全屏背景 */
            padding-top: 20px;
            /* 顶部留空 */
            background: #f0f2f5;
        }

        table {
            width: 90%;
            max-width: 1200px;
            border-collapse: separate;
            border-spacing: 0;
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            text-align: center;
        }

        th {
            background: #004aad;
            color: #fff;
            padding: 12px;
            font-size: 15px;
            text-align: center;
        }

        td {
            padding: 10px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
            text-align: center;
        }

        tbody tr:hover {
            background: #f1f7ff;
        }

        .nested-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 2px;
            justify-items: center;
            align-items: center;
        }

        .nested-grid div {
            background: #eef4ff;
            border-radius: 4px;
            padding: 4px;
            font-size: 12px;
            color: #004aad;
            text-align: center;
        }

        h2 {
            color: #004aad;
            text-align: center;
        }


        #floatingContainer {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            flex-direction: column;
            align-items: center;
            z-index: 9999;
        }

        .floating-tip {
            background: #d6442a;
            color: #fff;
            padding: 10px 16px;
            border-radius: 6px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            margin-top: 10px;
            opacity: 0;
            transform: translateY(-20px);
            transition: opacity 0.4s, transform 0.4s;
            max-width: 300px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .floating-tip.show {
            opacity: 1;
            transform: translateY(0);
        }

        .floating-tip button {
            background: none;
            border: none;
            color: #fff;
            font-weight: bold;
            font-size: 14px;
            cursor: pointer;
            margin-left: 10px;
        }

        a {
            color: #007bff;
            text-decoration: none;
            transition: color 0.3s, text-decoration 0.3s;
        }

        a:hover {
            color: #0056b3;
            text-decoration: underline;
        }

        /* 点击前后颜色保持一致 */
        a:visited,
        a:active {
            color: #bbc442;
        }

        .btn-link {
            display: inline-block;
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border-radius: 8px;
            text-decoration: none;
            transition: background-color 0.3s;
            margin-top: 10px;
        }

        .btn-link:hover {
            background-color: #218838;
        }

        .highlight-link {
            color: #bbc442;
            font-weight: bold;
        }

        .highlight-link:hover {
            color: #bbc442;
            text-decoration: underline;
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>联赛</th>
                <th>比赛球队</th>
                <th>比分</th>
                <th>时间</th>
                <th>红牌比分</th>
                <th>平博让球</th>
                <th>皇冠让球</th>
                <th> <a href="/rh.html" target="_blank">事件</a> </th>
            </tr>
        </thead>
        <tbody id="match-list">


        </tbody>
    </table>
    <input type="button" onclick="chage_ps()" id="ps_status_button" style="background-color: tomato;border: 1px solid #ccc; padding: 6px 12px;" value="开启平博数据更新"></button>

    <div id="floatingTip" class="floating-tip hide">
        <span id="floatingTipMessage" id="tips"></span>
        <button onclick="hideFloatingTip()">✕</button>
    </div>

    <div id="floatingContainer"></div>
</body>
<script src="/resources/common.js"></script>
<script>
    var MATCHES = []
    const beepSound = new Audio("1.mp3");
    // const socket = new WebSocket("ws://150.109.34.83:8081");
    const socket = new WebSocket(`ws://${IP}:8081`);
    socket.addEventListener("open", function (event) {
        socket.send(JSON.stringify({
            type: "red_history",
            data: ""
        }))
    });

    socket.addEventListener("message", function (event) {
        let data = JSON.parse(event.data)
        if (data.type == "full_data") {
            queueUpdate(data.data);
        }
        if (data.type == "titan007_red_card_change") {
            titan007_red_card_change(data)
        }
        if (data.type == "red_history") {
            red_history(data)
        }
    });

    socket.addEventListener("close", function (event) {
    })

    let pendingUpdates = new Map();
    function queueUpdate(data) {
        pendingUpdates = new Map();
        MATCHES = data
        for (let i = 0; i < data.length; i++) {
            let match = data[i]
            pendingUpdates.set(match.matchId, match);
        }
    }
    function applyUpdates() {
        pendingUpdates.forEach((match, matchId) => {
            updateMatch(matchId, match);
        });
        pendingUpdates.clear();
        requestAnimationFrame(applyUpdates);
    }

    requestAnimationFrame(applyUpdates);

    function updateMatch(matchId, match) {
        const container = document.getElementById("match-list");
        let el = createMatch(matchId, match)
        container.appendChild(el)
    }

    function createMatch(matchId, match) {
        const matchEl = document.createElement("tr");
        matchEl.className = "match-item";
        matchEl.id = match.matchId; // 用于后续更新
        let hgaMarkets = match.market.hga
        let psMarkets = match.market.ps3838
        let hgaMarketsEl = ""
        if (hgaMarkets.length > 0) {
            for (let i = 0; i < hgaMarkets.length; i++) {
                let market = hgaMarkets[i];
                if (market.type == "滚球让球") {
                    hgaMarketsEl = hgaMarketsEl + `
                        <div>${market.homeOdds}</div>
                        <div>${market.handicap}</div>
                        <div>${market.awayOdds}</div>
                    `
                }
            }
        }
        let psMarketsEl = ""
        if (psMarkets.handap.length == 0) {
            if (document.getElementById(`${match.matchId}_psMarkets`) && match.psMarketStatus != 2) {
                psMarketsEl = document.getElementById(`${match.matchId}_psMarkets`).getHTML();
            }
            // console.info("未更新平博" + `${match.home} vs ${match.away} || ${match.psMarketStatus}`)
        }
        if (psMarkets.handap.length > 0) {
            for (let i = 0; i < psMarkets.handap.length && i < 3; i++) {
                let market = psMarkets.handap[i];
                psMarketsEl = psMarketsEl + `
                        <div>${market.a}</div>
                        <div>${market.v}</div>
                        <div>${market.b}</div>
                    `
            }
        }
        let period = match.time
        let periods = period.split("^")
        let prd = periods[0] == "2H" ? "下半场" : periods[0] == "1H" ? "上半场" : periods[0] == "MTIME" ? "中场" : "未知"
        let tm = periods[1]
        matchEl.innerHTML = `
        <tr >
                <td>${match.league}</td>
                <td><a href="/odds.html?id=${match.matchId}" class="highlight-link" target="_blank"> ${match.home} vs ${match.away}</a></td>
                <td>${match.score}</td>
                <td>${prd}  ${tm}</td>
                <td>${match.redScore}</td>
                <td>
                    <div class="nested-grid" id="${match.matchId}_psMarkets">
                        ${psMarketsEl}
                    </div>
                </td>
                <td>
                    <div class="nested-grid">
                        ${hgaMarketsEl}
                    </div>
                </td>
                <td>${redHistory.indexOf(match.matchId) >= 0 ? `<a href="/odds.html?id=${match.matchId}" class="highlight-link" target="_blank">监控到红牌</a>` : "无"}</td>
            </tr>
        `
        const matchElement = document.getElementById(`${matchId}`);
        if (matchElement) {
            matchElement.remove()
        }
        return matchEl
    }

    function titan007_red_card_change(data) {
        let message = `${data.data.team1} v ${data.data.team2} 出现红牌 ${data.data.redCardOld} ==> ${data.data.redCardCount}`
        console.info("红牌:" + message)
        for (let i = 0; i < MATCHES.length; i++) {
            let value = MATCHES[i]
            console.info("定位比赛:" + value.home)
            if (value.home == data.data.team1) {
                showFloatingTip(message, data.data.matchId, duration = 20000)
                console.info(message)
                break
            }
        }
        socket.send(JSON.stringify({
            type: "red_history",
            data: ""
        }))
    }

    var redHistory = []
    function red_history(data) {
        for (let i = 0; i < data.data.length; i++) {
            let matchId = data.data[i].matchId
            redHistory.push(matchId)
        }
    }

    function showFloatingTip(message, id, duration = 20000) {
        const container = document.getElementById('floatingContainer');
        const tip = document.createElement('div');
        tip.id = `${id}_tip`
        tip.className = 'floating-tip';
        tip.innerHTML = `
            <span>${message}</span>
            <button onclick="this.parentElement.remove()">✕</button>
        `;
        tip.onclick = function () {
            window.open(`/odds.html?id=${this.id.split("_")[0]}`, '_blank');
        }
        container.appendChild(tip);

        // 强制重绘以触发动画
        requestAnimationFrame(() => {
            tip.classList.add('show');
        });
        beepSound.currentTime = 0; // 重置播放位置
        beepSound.play().catch(e => {
            console.log('提示音播放被阻止，用户可能未与页面交互');
        });
        // 自动关闭
        setTimeout(() => {
            tip.classList.remove('show');
            setTimeout(() => {
                tip.remove();
            }, 400);
        }, duration);
    }

    var ps_status = "CLOSE";

    function chage_ps() {
        if (ps_status == "CLOSE") {
            ps_status = "OPEN"
            document.getElementById("ps_status_button").style.backgroundColor = "rgb(40, 167, 35)"
            document.getElementById("ps_status_button").value = "关闭平博数据更新"
        } else {
            ps_status = "CLOSE"
            document.getElementById("ps_status_button").style.backgroundColor = "tomato"
            document.getElementById("ps_status_button").value = "开启平博数据更新"
        }
        socket.send(JSON.stringify({
            type: "change_status",
            data: ps_status
        }))
    }


    function unlockAudio(audio) {
        function unlock() {
            audio.play().then(() => {
                audio.pause();
                audio.currentTime = 0;
                document.removeEventListener('click', unlock);
                document.removeEventListener('touchstart', unlock);
                console.log('提示音已解锁，可正常播放');
            }).catch((e) => {
                console.log('解锁提示音失败', e);
            });
        }
        document.addEventListener('click', unlock);
        document.addEventListener('touchstart', unlock);
    }
    unlockAudio(beepSound);
</script>

</html>